# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# 建立者:       加一
# Name:         demo4.29
# Description:  列表方法
# Author:       加一
# Date:         2019/1/18
#-------------------------------------------------------------------------------

print("----测试append----")
numbers = [1,2,3,4]
numbers.append(5)
print(numbers)
numbers.append([6,7])
print(numbers)

print("----测试clear方法----")
names = ["bill","marry","jack"]
print(names)
names.clear();
print(names)

print("----测试copy方法----")
a = [1,2,3]
b = a
b[1] = 30
print(a)

aa = [1,2,3]
bb = aa.copy()
bb[1] = 30
print(aa)

print("----测试count方法----")
search = ["he","new","he","he","world","peter",[1,2,3],"ok",[1,2,3]]
# 搜索"he"在search出现的次数，运行结果：3
print(search.count("he"))
# 搜索[1,2,3]在search出现的次数，运行结果：2
print(search.count([1,2,3]))

print("----测试extend方法----")
a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a)

# 如果使用列表连接操作，效率会更低，并不建议使用
a = [1,2,3]
b = [4,5,6]
print(a + b)

# 可以使用分片赋值的方法实现同样的效果
a = [1,2,3]
b = [4,5,6]
a[len(a):] = b
print(a)

print("----测试index方法----")
s = ["I","love","python"];
print(s.index("python"))
print("xyz在列表中不存在，所哟搜索时会抛出异常")
# str.index("xyz")

print("----测试insert方法----")
numbers = [1,2,3,4,5]
numbers.insert(3,"four")
print(numbers)
# 可以使用分片赋值实现同样的效果
numbers = [1,2,3,4,5]
numbers[3:3] = ['four']
print(numbers)

print("----测试pop方法----")
numbers = [1,2,3]
# pop方法返回删除的元素值
print(numbers.pop())
print(numbers.pop(0))
print(numbers)

print("----测试remove方法----")
words = ["he","new","he","yes","bike"]
words.remove("he")
print(words)
# words.remove("ok")

print("----测试reverse方法----")
numbers = [1,2,3,4,5,6]
numbers.reverse()
print(numbers)

print("----测试sort方法----")
numbers = [5,4,1,7,4,2]
numbers.sort()
print(numbers)

values = [6,5,2,7,"aa","bb","cc"]
# 待排序列表的元素类型必须是可比较的，字符串和数值类型不能直接比较，否则会抛出异常
# values.sort()

# 使用sort方法排序，会直接修改原列表，如果要想对列表的副本进行排序，可以使用下面的代码
# 方法1 ：使用分片操作
x = [5,4,1,8,6]
y = x[:]
y.sort();
print(x)
print(y)

# 方法2 : 使用sorted函数
x = [7,6,4,8,5]
y = sorted(x)
print(x)
print(y)

# sorted函数可以对任何序列进行排序，例如对字符串进行排序
print(sorted("geekori"))

x = [5,4,1,7,5]
x.sort(reverse=True)
print(x)